﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using SAPbouiCOM;
using BoAddonBiz_FreightForwarder.UpLoad;
using BoAddonBiz_FreightForwarder;
using SAPbobsCOM;

namespace BoAddonBiz_FreightForwarder.Air.AirPortWork.Warehouse
{
    [BoAddonBiz_FreightForwarder.BusinessBase.ControlB1Form(IsNew = true, FormType = B1FormTypes.ado_AVA_FF_BJSWarehouse_IN)]
    public class B1Form_Warehouse_In : SAPBoAddon.B1Form
    {
        int CargoCurrentOffset = 0;//货物信息的当前行
        #region override
        protected override bool BeforeSaveCheckFormData()
        {
            return true;
        }

        protected override void FormEditModeChange(SAPBoAddon.frmItemEditMode frmEditMode)
        {
        }

        protected override void FormInfoSetting(SAPBoAddon.B1FormSetting FormSetting)
        {
            FormSetting.FormType = B1FormTypes.ado_AVA_FF_BJSWarehouse_IN;
            FormSetting.FormFileName = "AVA_FF_StorageBJSInForm.srf";

            #region 控件是否可编辑
            FormSetting.FormModeSetting.itmNewModeEnable = Utils.GetFormItems(FormSetting.FormXmlDocument);
            FormSetting.FormModeSetting.itmNewModeDisable = new string[] { "17", "l_base", "3", "11" };

            FormSetting.FormModeSetting.StatusItemUID = "7";
            SAPBoAddon.BrowseModeSetting BrowseModeSetting;
            #region P状态
            BrowseModeSetting = FormSetting.FormModeSetting.BrowseModeSettingList.Add();
            BrowseModeSetting.Status = "P";
            //P状态下可编辑的状态
            BrowseModeSetting.itmBrowseModeEnable = Utils.GetFormItems(FormSetting.FormXmlDocument);
            //P状态下不可编辑的状态
            BrowseModeSetting.itmBrowseModeDisable = new string[] { "3", "17", "l_base", "13", "Previous", "Next", "Survey", "76", "77", "79", "80" };
            #endregion
            #region R,C,D
            BrowseModeSetting = FormSetting.FormModeSetting.BrowseModeSettingList.Add();
            BrowseModeSetting.Status = "R";
            BrowseModeSetting.itmBrowseModeDisable = Utils.GetFormItems(FormSetting.FormXmlDocument);
            BrowseModeSetting = FormSetting.FormModeSetting.BrowseModeSettingList.Add();
            BrowseModeSetting.Status = "C";
            BrowseModeSetting.itmBrowseModeEnable = new string[] { "btnCancel" };
            BrowseModeSetting.itmBrowseModeDisable = Utils.GetFormItems(FormSetting.FormXmlDocument, true, new string[] { "btnCancel" });
            BrowseModeSetting = FormSetting.FormModeSetting.BrowseModeSettingList.Add();
            BrowseModeSetting.Status = "D";
            BrowseModeSetting.itmBrowseModeDisable = Utils.GetFormItems(FormSetting.FormXmlDocument);
            #endregion
            FormSetting.FormModeSetting.itmFindModeEnable = Utils.GetFormItems(FormSetting.FormXmlDocument);
            #endregion
        }

        protected override void InitializeForm(SAPBoAddon.B1FormInitializePar InitPar)
        {
            if (new Regex(@"\b\d+\b").Match(InitPar.FatherFormUID).Success)
            {
                this.CurrentForm.Mode = SAPbouiCOM.BoFormMode.fm_FIND_MODE;
                SAPBoAddon.B1Assistant.Item.SetValue(this.CurrentForm, this.CurrentForm.DataBrowser.BrowseBy, InitPar.FatherFormUID);
                this.CurrentForm.Items.Item("1").Click(SAPbouiCOM.BoCellClickType.ct_Regular);
            }
            #region 加载下拉列表框数据
            SAPbobsCOM.Recordset rs = SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
            //根据员工主数据上配置的此人是否是有什么样的类型进行配置 --Vincent.yin
            int UserID = SAPBoAddon.B1Addon.B1Addon.SBOCompany.UserSignature;
            rs.DoQuery(@"SElECT T4.Code
                                                        FROM OUSR T0
	                                                        INNER JOIN OHEM T1 ON T0.UserID = T1.UserID
	                                                        INNER JOIN [@AVA_OHEM] T2 ON T1.U_BusinessType = T2.Code
	                                                        INNER JOIN [@AVA_HEM1] T3 ON T2.Code = T3.Code
	                                                        INNER JOIN [@AVA_FF_OMOT] T4 ON T3.U_BusinessType = T4.Code
                                                        Where  T0.UserID = " + UserID);
            if (rs.RecordCount <= 0)
            {
                Utils.ComboBox_InitialItem(rs, CurrentForm.Items.Item("13"), "Code", "Name", "@AVA_FF_OMOT", null, "Where U_Type='Air' or U_Type IS NULL", true, false);//运输方式
            }
            else
            {
                Utils.ComboBox_InitialItem(rs, CurrentForm.Items.Item("13"), "T4.Code", "T4.Name", "OUSR", null, string.Format(@" T0
	                                                                                                                                    INNER JOIN OHEM T1 ON T0.UserID = T1.UserID
	                                                                                                                                    INNER JOIN [@AVA_OHEM] T2 ON T1.U_BusinessType = T2.Code
	                                                                                                                                    INNER JOIN [@AVA_HEM1] T3 ON T2.Code = T3.Code
	                                                                                                                                    INNER JOIN [@AVA_FF_OMOT] T4 ON T3.U_BusinessType = T4.Code
                                                                                                                                    Where T0.UserID ={0}                                                                                                                                                                                                                     
                                                                                                                                    ", UserID), true, false);//运输方式
            }
            Utils.InitialItemComboBox(SBOCompany, CurrentForm.Items.Item("19"), "Code", "Name", "@AVA_FF_CATY", null, String.Empty, null, true, true);
            //加载用户
            Utils.LoadUser(this.CurrentForm, this.SBOCompany, "61");
            #endregion
        }
        #endregion
        #region constructor
        public B1Form_Warehouse_In()
        {
            this.frm_ChooseFormListEvent += new SAPBoAddon.IB1FormEvents.B1ChooseFormListEventEventHandler(B1Form_Warehouse_In_frm_ChooseFormListEvent);
            this.frm_ItemEvent += new SAPBoAddon.IB1FormEvents.B1ItemEventEventHandler(B1Form_Warehouse_In_frm_ItemEvent);
            this.frm_FormDataEvent += new SAPBoAddon.IB1FormEvents.B1FormDataEventEventHandler(B1Form_Warehouse_In_frm_FormDataEvent);
            this.frm_MenuEvent += new SAPBoAddon.IB1FormEvents.B1MenuEventEventHandler(B1Form_Warehouse_In_frm_MenuEvent);
        }

        #endregion
        #region events
        void B1Form_Warehouse_In_frm_MenuEvent(SAPBoAddon.B1AddonBase.B1MenuEvent pVal, ref bool BubbleEvent)
        {
            if (pVal.BeforeAction)
            {
                #region 数据所有权-控制机场操作人员人能看到海翔库的单子
                //上一条、下一条,//第一条、最后一条
                if (pVal.MenuUID == B1MenuTypes.ado_SYS_Previous || pVal.MenuUID == B1MenuTypes.ado_SYS_Next || pVal.MenuUID == B1MenuTypes.ado_SYS_First || pVal.MenuUID == B1MenuTypes.ado_SYS_Last)
                {
                    //SBOApp.MessageBox("test");
                }
                #endregion
            }
            else
            {
                if (pVal.MenuUID == B1MenuTypes.sys_Add)
                {
                    GetSerialNumberByProc(CurrentForm);
                    CurrentForm.DataSources.DBDataSources.Item("@AVA_FF_OSTG").SetValue("U_DocDate", 0, DateTime.Now.ToString("yyyyMMdd"));
                    CurrentForm.DataSources.DBDataSources.Item("@AVA_FF_OSTG").SetValue("U_Operator", 0, SBOCompany.UserSignature.ToString());
                }
            }
        }

        void B1Form_Warehouse_In_frm_FormDataEvent(SAPBoAddon.B1AddonBase.B1BusinessObjectInfo pVal, ref bool BubbleEvent)
        {
            if (pVal.BeforeAction)
            {
                #region 添加新的业务单
                //                if (pVal.EventType == BoEventTypes.et_FORM_DATA_ADD)
                //                {
                //                    try
                //                    {
                //                        SAPbobsCOM.Recordset rs = SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
                //                        SAPbouiCOM.DBDataSource dbds = CurrentForm.DataSources.DBDataSources.Item("@AVA_FF_OSTG");
                //                        string SQL = @"
                //                                Declare @DocEntry int
                //                                Declare @SerialNum nvarchar(max)
                //                                SELECT @DocEntry = AutoKey FROM ONNM Where ObjectCode = 'AVA_FF_BusinessOpera'
                //
                //                                create table #temp (sernum nvarchar(max))
                //                                insert #temp EXEC AVA_AL_GetSerialNumber N'AVA_FF_BusinessOpera',N'{1}' 
                //                                select @SerialNum = sernum from #temp
                //                                drop table #temp
                //
                //                                Insert Into [@AVA_FF_OBNO] (DocEntry,DocNum,Period,Instance,Series,Handwrtten,Canceled,Object,UserSign,Transfered,Status,CreateDate,CreateTime,DataSource
                //	                                ,U_DocDate,U_TransportType,U_SerialNum,U_MBLNumber,U_SBLNumber,U_Status,U_CardCode,U_CardName,U_CntctCode,U_IsWarehouse)
                //	                                Values
                //	                                (@DocEntry,@DocEntry,8,0,43,'N','N','AVA_FF_BusinessOpera',{0},'N','O',CONVERT(char(10),getdate(),120),cast(datepart(hh,getdate()) as int)*100 + cast(datepart(mi,getdate()) as int),'I'
                //	                                ,GETDATE(),'{1}',@SerialNum,'{2}','{3}','P','{4}','{5}','{6}','N')
                //
                //                                UPDATE ONNM SET AutoKey = @DocEntry + 1 Where ObjectCode = 'AVA_FF_BusinessOpera'
                //                                ";
                //                        SQL = string.Format(SQL, SBOCompany.UserSignature.ToString(),
                //                                            dbds.GetValue("U_TransportType", dbds.Offset),
                //                                            dbds.GetValue("U_MBLNumber", dbds.Offset),
                //                                            dbds.GetValue("U_SBLNumber", dbds.Offset),
                //                                            dbds.GetValue("U_CardCode", dbds.Offset),
                //                                            dbds.GetValue("U_CardName", dbds.Offset),
                //                                            dbds.GetValue("U_CntctCode", dbds.Offset));
                //                        rs.DoQuery(SQL);
                //                    }
                //                    catch
                //                    {
                //                        BubbleEvent = false;
                //                    }
                //                }
                #endregion
                #region 更新ATA
                if (pVal.EventType == BoEventTypes.et_FORM_DATA_ADD || pVal.EventType == BoEventTypes.et_FORM_DATA_UPDATE)
                {
                    this.UpdateBOATA();
                }
                #endregion
            }
        }

        void B1Form_Warehouse_In_frm_ChooseFormListEvent(SAPBoAddon.B1AddonBase.B1ChooseFormList pVal, ref bool BubbleEvent)
        {
            if (pVal.Before_Action)
            {
                SAPbouiCOM.ChooseFromList cfl = this.CurrentForm.ChooseFromLists.Item(pVal.ChooseFromListUID);
                SAPbouiCOM.Conditions cons;
                SAPbouiCOM.Condition con;
                switch (pVal.ChooseFromListUID)
                {
                    case "CFL_CardCode"://客户
                        cons = new SAPbouiCOM.Conditions();
                        con = cons.Add();
                        con.Alias = "QryGroup13";
                        con.CondVal = "Y";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        con.Relationship = BoConditionRelationship.cr_AND;
                        con = cons.Add();
                        con.Alias = "CardType";
                        con.CondVal = "C";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        con.Relationship = BoConditionRelationship.cr_AND;
                        con = cons.Add();
                        con.Alias = "validFor";
                        con.CondVal = "Y";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        cfl.SetConditions(cons);
                        break;
                    case "CFL_Card"://委托
                        cons = new SAPbouiCOM.Conditions();
                        con = cons.Add();
                        con.Alias = "CardType";
                        con.CondVal = "S";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        con.Relationship = BoConditionRelationship.cr_AND;
                        con = cons.Add();
                        con.Alias = "validFor";
                        con.CondVal = "Y";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        cfl.SetConditions(cons);
                        break;
                    case "CFL_OCRD_O"://调单单位名称
                        cons = new SAPbouiCOM.Conditions();
                        con = cons.Add();
                        con.Alias = "validFor";
                        con.CondVal = "Y";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        cfl.SetConditions(cons);
                        break;
                    case "CFL_Close"://结算单位
                        cons = new SAPbouiCOM.Conditions();
                        con = cons.Add();
                        con.Alias = "CardType";
                        con.CondVal = "C";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        con.Relationship = BoConditionRelationship.cr_AND;
                        con = cons.Add();
                        con.Alias = "validFor";
                        con.CondVal = "Y";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        con.Relationship = BoConditionRelationship.cr_AND;
                        con = cons.Add();
                        con.Alias = "QryGroup14";
                        con.CondVal = "Y";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        cfl.SetConditions(cons);
                        break;
                }
            }
            else
            {
                if (pVal.Action_Success)
                {
                    SAPbouiCOM.DBDataSource dbds = this.CurrentForm.DataSources.DBDataSources.Item("@AVA_FF_STG1");
                    if (pVal.ChooseFromListUID == "CFL_Card")//委托单位
                    {
                        dbds.SetValue("U_DelCode", dbds.Offset, pVal.SelectedObjects.GetValue("CardCode", 0).ToString());
                        dbds.SetValue("U_delName", dbds.Offset, string.IsNullOrEmpty(pVal.SelectedObjects.GetValue("CardName", 0).ToString()) ? pVal.SelectedObjects.GetValue("CardFName", 0).ToString() : pVal.SelectedObjects.GetValue("CardName", 0).ToString());
                    }
                    if (pVal.ChooseFromListUID == "CFL_CardCode")//客户
                    {
                        dbds.SetValue("U_CardCode", dbds.Offset, pVal.SelectedObjects.GetValue("CardCode", 0).ToString());
                        dbds.SetValue("U_CardName", dbds.Offset, pVal.SelectedObjects.GetValue("CardName", 0).ToString());
                        dynamic Cntct = Utils.GetDefaultContractPerson(this.SBOCompany, pVal.SelectedObjects.GetValue("CardCode", 0).ToString());
                        if (Cntct != null)
                        {
                            dbds.SetValue("U_CntctCode", dbds.Offset, Cntct.FullName);
                        }
                        //Utils.GetSalesPerson(dbds, pVal.SelectedObjects.GetValue("CardCode", 0).ToString());
                    }
                    if (pVal.ChooseFromListUID == "CFL_OCRD_O")//调单单位
                    {
                        dbds.SetValue("U_OutOrderCardCode", dbds.Offset, pVal.SelectedObjects.GetValue("CardCode", 0).ToString());
                        dbds.SetValue("U_OutOrderCardName", dbds.Offset, string.IsNullOrEmpty(pVal.SelectedObjects.GetValue("CardName", 0).ToString()) ? pVal.SelectedObjects.GetValue("CardFName", 0).ToString() : pVal.SelectedObjects.GetValue("CardName", 0).ToString());
                        dynamic Cntct = Utils.GetDefaultContractPerson(this.SBOCompany, pVal.SelectedObjects.GetValue("CardCode", 0).ToString());
                        if (Cntct != null)
                        {
                            dbds.SetValue("U_OutOrderCntct", dbds.Offset, Cntct.FullName);
                            dbds.SetValue("U_OutOrderPhone", dbds.Offset, Cntct.Cellolar);
                        }
                    }
                    if (pVal.ChooseFromListUID == "CFL_Close")//结算单位
                    {
                        dbds.SetValue("U_DelCode", dbds.Offset, pVal.SelectedObjects.GetValue("CardCode", 0).ToString());
                        dbds.SetValue("U_DelName", dbds.Offset, pVal.SelectedObjects.GetValue("CardName", 0).ToString());
                    }
                }
            }

        }

        void B1Form_Warehouse_In_frm_ItemEvent(SAPBoAddon.B1AddonBase.B1ItemEvent pVal, ref bool BubbleEvent)
        {
            if (pVal.Before_Action)
            {
                #region 数据所有权-控制机场操作人员人能看到海翔库的单子

                #endregion
            }
            else
            {
                #region pane
                if (pVal.ItemUID == "tab_0" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    CurrentForm.PaneLevel = 1;
                }
                if (pVal.ItemUID == "tab_1" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    CurrentForm.PaneLevel = 2;
                }
                #endregion
                #region  货物信息
                //上一条
                if (pVal.ItemUID == "Previous" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    CargoCurrentOffset = Utils.Previous(SBOApp, pVal.FormUID, "@AVA_FF_STG1");
                    Utils.ShowDBDSNum(CurrentForm, "@AVA_FF_STG1", CargoCurrentOffset);/*货物显示行号、总行数*/
                }
                //下一条
                if (pVal.ItemUID == "Next" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    CargoCurrentOffset = Utils.Next(SBOApp, pVal.FormUID, "@AVA_FF_STG1");
                    Utils.ShowDBDSNum(CurrentForm, "@AVA_FF_STG1", CargoCurrentOffset);/*货物显示行号、总行数*/
                }
                //添加
                if (pVal.ItemUID == "Add" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    CargoCurrentOffset = Utils.Add(SBOApp, pVal.FormUID, "@AVA_FF_STG1");
                    Utils.ShowDBDSNum(CurrentForm, "@AVA_FF_STG1", CargoCurrentOffset);/*货物显示行号、总行数*/
                }
                //删除
                if (pVal.ItemUID == "Del" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    CargoCurrentOffset = Utils.Delete(SBOApp, pVal.FormUID, "@AVA_FF_STG1", CargoCurrentOffset);
                    Utils.ShowDBDSNum(CurrentForm, "@AVA_FF_STG1", CargoCurrentOffset);/*货物显示行号、总行数*/
                }
                //浏览所有
                if (pVal.ItemUID == "Survey" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    Utils.Survey(SBOApp, SBOCompany, pVal.FormUID, "@AVA_FF_STG1");
                    Utils.ShowDBDSNum(CurrentForm, "@AVA_FF_STG1", CargoCurrentOffset);/*货物显示行号、总行数*/
                }
                #endregion
                #region 添加
                if (pVal.ItemUID == "btn_add" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    SBOApp.Menus.Item(B1MenuTypes.sys_Add).Activate();
                }
                #endregion
                #region 单据编码
                if (pVal.ItemUID == "13" && pVal.EventType == BoEventTypes.et_COMBO_SELECT && pVal.ItemChanged)
                {
                    GetSerialNumberByProc(CurrentForm);
                }
                #endregion
                #region 附件
                //选择文件路径
                if (pVal.ItemUID == "Upload" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    Common_UpLoad upload = new Common_UpLoad();
                    upload.SetAffixInfo(CurrentForm, "@AVA_FF_OSTG", 0);
                }
                //下载上传的文件
                if (pVal.ItemUID == "Down" && pVal.EventType == BoEventTypes.et_CLICK)
                {
                    Common_UpLoad Uploading = new Common_UpLoad();
                    Uploading.DownFile(CurrentForm, "@AVA_FF_OSTG", 0);
                }
                #endregion
                #region 制作费用
                /*制作费用按钮单击*/
                if (pVal.ItemUID == "btnCharge" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    if (string.IsNullOrEmpty(SAPBoAddon.B1Assistant.Item.GetValue(CurrentForm, "19").ToString().Trim()))
                    {
                        SBOApp.MessageBox("请输入货物类型，并保存了此单据！");
                    }
                    else
                        if (string.IsNullOrEmpty(SAPBoAddon.B1Assistant.Item.GetValue(CurrentForm, "42").ToString().Trim()))
                        {
                            SBOApp.MessageBox("请输入入库日期，并保存了此单据！");
                        }
                        else
                            if (string.IsNullOrEmpty(SAPBoAddon.B1Assistant.Item.GetValue(CurrentForm, "44").ToString().Trim()))
                            {
                                SBOApp.MessageBox("请输入出库日期，并保存了此单据！");
                            }
                            else
                                if (string.IsNullOrEmpty(SAPBoAddon.B1Assistant.Item.GetValue(CurrentForm, "CloseName").ToString().Trim()))
                                {
                                    SBOApp.MessageBox("请检查结算单据是否选择，并保存了此单据！");
                                }
                                else if (string.IsNullOrEmpty(SAPBoAddon.B1Assistant.Item.GetValue(CurrentForm, "InvType").ToString().Trim()))
                                {
                                    SBOApp.MessageBox("请检查发票类型是否选择，并保存了此单据！");
                                }
                                else
                                    if (CurrentForm.Mode != BoFormMode.fm_OK_MODE)
                                    {
                                        SBOApp.MessageBox("请检查结算单据是否选择，并保存了此单据！");
                                    }
                                    else
                                        if (string.IsNullOrEmpty(SAPBoAddon.B1Assistant.Item.GetValue(CurrentForm, "Delivery").ToString().Trim()))
                                        {
                                            CreateCharge();
                                        }
                                        else
                                        {
                                            SBOApp.MessageBox("此单据已生成账单，不能重复出账单！");
                                        }
                }
                #endregion
                #region LinkButton
                if (pVal.ItemUID == "BOLink" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    Utils.OpenUserDeFinedObjectForm(this.CurrentForm, pVal.ItemUID, "AVA_FF_BusinessOpera");
                }
                if (new string[] { "s2", "s8" }.Contains<string>(pVal.ItemUID) && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    Utils.OpenUserDeFinedObjectForm(this.CurrentForm, pVal.ItemUID, "AVA_FF_Port");
                }
                #endregion
                if (pVal.ItemUID == "btnCancel" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    CancelDelivery();
                }
            }
        }
        #endregion
        #region private methods
        public void GetSerialNumberByProc(SAPbouiCOM.Form oForm)
        {
            string mySerialNumber = string.Empty;
            SAPbouiCOM.DBDataSource dbds;
            SAPbobsCOM.Recordset oRst;
            string TransportType = string.Empty;
            string SQL = string.Empty;
            oRst = SAPBoAddon.B1Addon.B1Addon.SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
            dbds = oForm.DataSources.DBDataSources.Item(oForm.Items.Item(oForm.DataBrowser.BrowseBy).Specific.DataBind.TableName);
            //获取当前单据类型
            TransportType = dbds.GetValue("U_TransportType", dbds.Offset).Trim();
            string BusinessObjectCode = oForm.BusinessObject.Type;
            SQL = string.Format("EXEC AVA_AL_GetSerialNumber N'{0}',N'{1}'  ", BusinessObjectCode, TransportType);
            oRst.DoQuery(SQL);
            if (oRst.RecordCount > 0)
            {
                mySerialNumber = oRst.Fields.Item("SerNum").Value;
                dbds.SetValue("U_BaseSerial", dbds.Offset, mySerialNumber);
                oRst.DoQuery("SELECT AUTOKEY FROM [ONNM] WHERE ObjectCode = 'AVA_FF_BusinessOpera'");
                if (oRst.RecordCount > 0)
                    dbds.SetValue("U_BaseEntry", dbds.Offset, oRst.Fields.Item("AUTOKEY").Value);
            }
        }

        private void UpdateBOATA()
        {
            string BaseEntry = CurrentForm.DataSources.DBDataSources.Item("@AVA_FF_OSTG").GetValue("U_BaseEntry", 0).Trim();
            string ATA = CurrentForm.DataSources.DBDataSources.Item("@AVA_FF_STG1").GetValue("U_ATA", 0).Trim();
            string ATATime = CurrentForm.DataSources.DBDataSources.Item("@AVA_FF_STG1").GetValue("U_ATATime", 0).Trim();
            string RCDate = CurrentForm.DataSources.DBDataSources.Item("@AVA_FF_STG1").GetValue("U_RCDate", 0).Trim();
            string RCTime = CurrentForm.DataSources.DBDataSources.Item("@AVA_FF_STG1").GetValue("U_RCTime", 0).Trim();
            string ClearedDate = CurrentForm.DataSources.DBDataSources.Item("@AVA_FF_STG1").GetValue("U_ClearedDate", 0).Trim();
            string ClearedTime = CurrentForm.DataSources.DBDataSources.Item("@AVA_FF_STG1").GetValue("U_ClearedTime", 0).Trim();
            string DeliveryDate = CurrentForm.DataSources.DBDataSources.Item("@AVA_FF_STG1").GetValue("U_DeliveryDate", 0).Trim();
            string DeliveryTime = CurrentForm.DataSources.DBDataSources.Item("@AVA_FF_STG1").GetValue("U_DeliveryTime", 0).Trim();
            string Signer = CurrentForm.DataSources.DBDataSources.Item("@AVA_FF_STG1").GetValue("U_Signer", 0).Trim();

            SAPbobsCOM.Recordset rs = SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
            string SQL = @"UPDATE [@AVA_FF_OBNO]  SET 
            U_RCDate={1},U_RCTime={2},U_ClearedDate={3},U_ClearedTime={4},
            U_DeliveryDate={5},U_DeliveryTime={6},U_ATA={7},U_ATATime={8},
            U_Signer={9}
             Where DocEntry = {0}";
            SQL = string.Format(SQL,
                BaseEntry,
                string.IsNullOrEmpty(RCDate) ? "U_RCDate" : string.Format("N'{0}'", RCDate),
                string.IsNullOrEmpty(RCTime) ? "U_RCTime" : string.Format("{0}", RCTime),
                string.IsNullOrEmpty(ClearedDate) ? "U_ClearedDate" : string.Format("N'{0}'", ClearedDate),
                string.IsNullOrEmpty(ClearedTime) ? "U_ClearedTime" : string.Format("{0}", ClearedTime),
                string.IsNullOrEmpty(DeliveryDate) ? "U_DeliveryDate" : string.Format("N'{0}'", DeliveryDate),
                string.IsNullOrEmpty(DeliveryTime) ? "U_DeliveryTime" : string.Format("{0}", DeliveryTime),
                string.IsNullOrEmpty(ATA) ? "U_ATA" : string.Format("N'{0}'", ATA),
                string.IsNullOrEmpty(ATATime) ? "U_ATATime" : string.Format("{0}", ATATime),
                string.IsNullOrEmpty(Signer) ? "U_Signer" : string.Format("N'{0}'", Signer)
                );
            rs.DoQuery(SQL);

            #region 更新SEDL数据
            string SBLNumber = CurrentForm.DataSources.DBDataSources.Item("@AVA_FF_OSTG").GetValue("U_SBLNumber", 0).Trim();
            string SQL_UPD_SEDL = string.Empty;

            SQL_UPD_SEDL = string.Format(@"UPDATE [@AVA_SEDL] SET 
            U_RCDate={1},U_RCTime={2},U_ReleaseDate={3},U_ClearedTime={4},
            U_DeliveryDate={5},U_DeliveryTime={6},U_ATA={7},U_ATATime={8}
            WHERE U_SBLNumber=N'{0}'  ",
                SBLNumber,
                string.IsNullOrEmpty(RCDate) ? "U_RCDate" : string.Format("N'{0}'", RCDate),
                string.IsNullOrEmpty(RCTime) ? "U_RCTime" : string.Format("{0}", RCTime),
                string.IsNullOrEmpty(ClearedDate) ? "U_ReleaseDate" : string.Format("N'{0}'", ClearedDate),
                string.IsNullOrEmpty(ClearedTime) ? "U_ClearedTime" : string.Format("{0}", ClearedTime),
                string.IsNullOrEmpty(DeliveryDate) ? "U_DeliveryDate" : string.Format("N'{0}'", DeliveryDate),
                string.IsNullOrEmpty(DeliveryTime) ? "U_DeliveryTime" : string.Format("{0}", DeliveryTime),
                string.IsNullOrEmpty(ATA) ? "U_ATA" : string.Format("N'{0}'", ATA),
                string.IsNullOrEmpty(ATATime) ? "U_ATATime" : string.Format("{0}", ATATime)
                );
            rs.DoQuery(SQL_UPD_SEDL);
            #endregion

        }

        #region 制作费用
        private void CreateCharge()
        {
            string DocEntry = string.Empty;
            string CardCode = string.Empty;
            string CardName = string.Empty;
            string BP = string.Empty;
            string CargoType = string.Empty;
            double Weight;
            int Days;
            string IsTransfer = string.Empty;
            string BaseEntry = string.Empty;
            string BaseSerialNum = string.Empty;
            string InvType = string.Empty;

            SAPbobsCOM.Recordset rs = SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
            SAPbouiCOM.DBDataSource dbds = CurrentForm.DataSources.DBDataSources.Item("@AVA_FF_OSTG");
            SAPbouiCOM.DBDataSource dbds1 = CurrentForm.DataSources.DBDataSources.Item("@AVA_FF_STG1");

            DocEntry = dbds.GetValue("DocEntry", dbds.Offset).Trim();
            BaseEntry = dbds.GetValue("U_BaseEntry", dbds.Offset).Trim();
            BaseSerialNum = dbds.GetValue("U_BaseSerial", dbds.Offset).Trim();
            CardCode = dbds1.GetValue("U_DelCode", 0).Trim();
            CardName = dbds1.GetValue("U_DelName", 0).Trim();
            BP = dbds.GetValue("U_CardName", 0).Trim();
            CargoType = dbds1.GetValue("U_CargoType", 0).Trim();
            Weight = Convert.ToDouble(dbds1.GetValue("U_Weight", 0).Trim());
            Days = (Convert.ToDateTime(Utils.ToDatetime(dbds1.GetValue("U_OutDate", 0).Trim() == "" ? DateTime.Now.ToString() : dbds1.GetValue("U_OutDate", 0).Trim())) - Utils.ToDatetime(dbds1.GetValue("U_InDate", 0).Trim())).Days + 1;
            IsTransfer = dbds.GetValue("U_IsTransfer", dbds.Offset).Trim();
            InvType = dbds1.GetValue("U_InvoiceType", 0).Trim();
            #region 机场费用
            Charges charges = new Charges();
            charges.CardCode = CardCode;
            charges.CardName = CardName;
            charges.BaseEntry = BaseEntry;
            charges.BaseSerialNum = BaseSerialNum;
            Charge charge = null;
            #region 调单费
            charge = charges.New();
            charge.ItemCode = "F000074";
            charge.ItemName = "换单费";
            charge.ShortName = "HDF";
            charge.Unit = "票";//票
            switch (BP)
            {
                case "上海传奇国际货物运输代理有限公司":
                    charge.Price = 250;
                    break;
                case "力鹏国际物流（深圳）有限公司上海分公司":
                    charge.Price = 450;
                    break;
                default:
                    charge.Price = 200;
                    break;
            }
            //if (BP == "上海传奇国际货物运输代理有限公司")
            //    charge.Price = 250;
            //else
            //    charge.Price = 200;
            #endregion
            #region 舱单寻入费
            charge = charges.New();
            charge.ItemCode = "F000091";
            charge.ItemName = "录入费";
            charge.ShortName = "LRF";
            charge.Unit = "票";
            charge.Price = 30;
            #endregion
            #region 机场杂费及分拨费
            charge = charges.New();
            charge.ItemCode = "F000081";
            charge.ItemName = "机场费";
            charge.ShortName = "JCF";
            switch (CargoType)
            {
                case "General"://普货
                    #region 普货
                    if (0.85 * Weight > 60)
                    {
                        charge.Unit = "公斤";
                        charge.Price = 0.85 * Weight;
                        if (IsTransfer == "Y")//转关货
                            charge.Price = (0.85 + 0.4) * Weight;
                    }
                    else
                    {
                        charge.Unit = "票";
                        charge.Price = 60;
                        if (IsTransfer == "Y")//转关货
                            charge.Price = 60 + (Weight * 0.4);
                    }
                    #endregion
                    break;
                case "Fresh"://鲜活
                    break;
                case "Danger"://危险品
                    #region 危险品
                    if (0.95 * Weight > 60)
                    {
                        charge.Unit = "公斤";
                        charge.Price = 0.95 * Weight;
                        if (IsTransfer == "Y")//转关货
                            charge.Price = (0.95 + 0.4) * Weight;
                    }
                    else
                    {
                        charge.Unit = "票";
                        charge.Price = 60;
                        if (IsTransfer == "Y")//转关货
                            charge.Price = 60 + (Weight * 0.4);
                    }
                    #endregion
                    break;
                case "Cold"://冷藏
                    #region 冷藏
                    if (1.05 * Weight > 60)
                    {
                        charge.Unit = "公斤";
                        charge.Price = 1.05 * Weight;
                        if (IsTransfer == "Y")//转关货
                            charge.Price = (1.05 + 0.4) * Weight;
                    }
                    else
                    {
                        charge.Unit = "票";
                        charge.Price = 60;
                        if (IsTransfer == "Y")//转关货
                            charge.Price = 60 + (Weight * 0.4);
                    }
                    #endregion
                    break;
            }
            #endregion
            #region 叉车费
            charge = charges.New();
            charge.ItemCode = "F000035";
            charge.ItemName = "叉车费";
            charge.ShortName = "CLF";
            if (Weight < 500)
            {
                charge.Unit = "票";
                charge.Price = 50;
            }
            if (Weight > 500 && Weight < 1000)
            {
                charge.Unit = "票";
                charge.Price = 100;
            }
            if (Weight > 1000)
            {
                charge.Unit = "公斤";
                charge.Price = 0.1 * Weight;
            }
            #endregion
            #region 仓储费
            charge = charges.New();
            charge.ItemCode = "F000023";
            charge.ItemName = "仓储费";
            charge.ShortName = "CCF";
            switch (CargoType)
            {
                case "General"://普货
                    #region 小于3天免收仓储费
                    if (Days <= 3)
                    { }
                    #endregion
                    #region 大于3天小于11天的
                    if (Days > 3 && Days <= 10)
                    {
                        charge.Unit = "公斤";
                        charge.Price = 0.2 * Convert.ToDouble(Days - 3) * Weight;
                    }
                    #endregion
                    #region 大于10天加倍计收
                    if (Days > 10)
                    {

                        charge.Unit = "公斤";
                        charge.Price = (0.2 * 7 * Weight) + (0.4 * Convert.ToDouble(Days - 10) * Weight);
                    }
                    #endregion
                    #region 最低收费
                    if (Days > 3 && charge.Price <= 60)
                    {
                        charge.Unit = "票";
                        charge.Price = 60;
                    }
                    #endregion
                    break;
                case "Fresh"://鲜活
                    break;
                case "Danger"://危险品
                case "Cold"://冷藏
                    #region 小于5天
                    if (Days <= 5)
                    {
                        charge.Unit = "公斤";
                        charge.Price = 1 * Convert.ToDouble(Days) * Weight;
                    }
                    #endregion
                    #region 大于5天 加收一倍
                    if (Days > 5)
                    {
                        charge.Unit = "公斤";
                        charge.Price = (1 * Convert.ToDouble(5) * Weight) + (2 * Convert.ToDouble(Days - 5) * Weight);
                    }
                    #endregion
                    #region 最低收费100
                    if (charge.Price <= 100)
                    {
                        charge.Unit = "票";
                        charge.Price = 100;
                    }
                    #endregion
                    break;
            }
            #endregion
            #region 三检费
            charge = charges.New();
            charge.ItemCode = "F000161";
            charge.ItemName = "商检费";
            charge.ShortName = "CIC";
            charge.Unit = "票";//票
            charge.Price = 10;
            #endregion
            #region 生成销售订单
            if (SBOCompany.InTransaction == false) SBOCompany.StartTransaction();
            int SalesOrderNum = CreateSalesOrder(charges, InvType);
            int DeliveryNum = CreateDelivery(SalesOrderNum, charges.CardCode, charges.Where(line => line.Price > 0).Count()); ;
            rs.DoQuery("UPDATE [@AVA_FF_OSTG] SET U_Ref1 = '" + DeliveryNum.ToString() + "'/*,U_Status = 'C'*/ Where DocEntry = " + DocEntry);
            if (SBOCompany.InTransaction) SBOCompany.EndTransaction(BoWfTransOpt.wf_Commit);
            SBOApp.MessageBox("现结账单已生成。-- " + DeliveryNum.ToString() + "\r\n 请记住账号单，点击确定后系统弹出账单进行打印。\r\n如出现问题请手工点击“服务”模块中的“机场现结账单”进行打印。");
            CurrentForm.Mode = BoFormMode.fm_FIND_MODE;
            SAPBoAddon.B1Assistant.Item.SetEnabled(CurrentForm, "3", true);
            SAPBoAddon.B1Assistant.Item.SetValue(CurrentForm, "3", DocEntry);
            CurrentForm.Items.Item("1").Click(BoCellClickType.ct_Regular);
            PrintDelivery(DeliveryNum);
            #endregion
            #endregion
        }
        private int CreateSalesOrder(Charges charges, string InvType)
        {
            SAPbobsCOM.Documents Order = SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oOrders);
            Order.CardCode = charges.CardCode;
            Order.DocDate = DateTime.Now;
            Order.DocDueDate = DateTime.Now;
            Order.DocCurrency = "RMB";
            Order.ShipToCode = "";
            Order.UserFields.Fields.Item("U_InvoiceType").Value = InvType;
            #region lines
            foreach (var charge in charges)
            {
                if (charge.Price <= 0) continue;
                Order.Lines.SetCurrentLine(Order.Lines.Count - 1);
                Order.Lines.ItemCode = charge.ItemCode;
                switch (InvType)
                {
                    case "P"://专用发票6%
                    case "G"://普通发票6%
                        Order.Lines.Quantity = charge.Quantity * (1 + 0.06);
                        break;
                    case "S"://服务发票3%
                        Order.Lines.Quantity = charge.Quantity * (1 + 0.03);
                        break;
                    default://不开票
                        Order.Lines.Quantity = charge.Quantity;
                        break;
                }
                Order.Lines.BarCode = charge.ShortName;
                Order.Lines.UnitPrice = charge.Price;
                Order.Lines.DiscountPercent = 0d;
                Order.Lines.Currency = charge.Currency;//币种
                Order.Lines.Rate = charge.Rate;//汇率
                Order.Lines.FreeText = charge.FreeTxt;
                Order.Lines.TaxCode = "";
                Order.Lines.VatGroup = "";
                Order.Lines.ShipToCode = string.Empty;/*added by WangPeng 2012-7-11 防止客户的收货方地址编码更改引发的异常*/
                #region 自定义字段赋值
                Order.Lines.UserFields.Fields.Item("U_Enterman").Value = charge.Enterman;
                Order.Lines.UserFields.Fields.Item("U_EnterDate").Value = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
                Order.Lines.UserFields.Fields.Item("U_IsCheck").Value = "Y";
                //Order.Lines.UserFields.Fields.Item("U_CheckDate").Value = DateTime.Now;
                //Order.Lines.UserFields.Fields.Item("U_Checker").Value = charge.Enterman;
                //Order.Lines.UserFields.Fields.Item("U_BillNumber").Value = "";
                //Order.Lines.UserFields.Fields.Item("U_UnitMeasure").Value ="";
                //Order.Lines.UserFields.Fields.Item("U_IsShowTax").Value ="";
                Order.Lines.UserFields.Fields.Item("U_BoType").Value = charge.BaseType;
                Order.Lines.UserFields.Fields.Item("U_BoEntry").Value = charge.BaseEntry;
                Order.Lines.UserFields.Fields.Item("U_BoSerialNum").Value = charge.BaseSerialNum;
                Order.Lines.UserFields.Fields.Item("U_Cashier").Value = charge.Cashier;//收款负责人
                switch (InvType)
                {
                    case "P"://专用发票6%
                    case "G"://普通发票6%
                        Order.Lines.UserFields.Fields.Item("U_TaxRate").Value = 0.06;
                        break;
                    case "S"://服务发票3%
                        Order.Lines.UserFields.Fields.Item("U_TaxRate").Value = 0.03;
                        break;
                    default://不开票
                        Order.Lines.UserFields.Fields.Item("U_TaxRate").Value = 0;
                        break;
                }
                #endregion
                Order.Lines.Add();
            }
            #endregion
            int result = Order.Add();
            if (result != 0)
            {
                System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Order);
                string ErrMsg = string.Empty;
                if (SBOCompany.GetLastErrorCode() == -5002)
                {
                    ErrMsg = "“" + charges.CardName + "” 在业务伙伴 客户 中没有添加，请添加业务伙伴后再执行此操作。\r\n";
                }
                throw new Exception(ErrMsg + SBOCompany.GetLastErrorCode().ToString() + " -- " + SBOCompany.GetLastErrorDescription());
            }
            System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Order);
            return int.Parse(SBOCompany.GetNewObjectKey());
        }
        private int CreateDelivery(int SalesOrder, string CardCode, int Count)
        {
            SAPbobsCOM.Documents Delivery = SBOCompany.GetBusinessObject(BoObjectTypes.oDeliveryNotes);
            Delivery.CardCode = CardCode;
            Delivery.DocDate = DateTime.Now;
            for (int i = 0; i < Count; i++)
            {
                Delivery.Lines.SetCurrentLine(Delivery.Lines.Count - 1);
                Delivery.Lines.BaseType = 17;
                Delivery.Lines.BaseEntry = SalesOrder;
                Delivery.Lines.BaseLine = i;
                Delivery.Lines.Add();
            }
            if (Delivery.Add() != 0)
            {
                System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Delivery);

                throw new Exception(SBOCompany.GetLastErrorCode().ToString() + " -- " + SBOCompany.GetLastErrorDescription());
            }
            System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Delivery);
            return int.Parse(SBOCompany.GetNewObjectKey());
        }
        private void PrintDelivery(int Delivery)
        {
            Utils.SetPrintSetting(SBOApp, "机场现结账单.rpt", Delivery.ToString());
        }
        #region Module
        protected class Charge
        {
            public string ItemCode { get; set; }
            public string ItemName { get; set; }
            public string ShortName { get; set; }
            public string Currency { get { return "RMB"; } }
            public double Rate { get { return 1; } }
            public string FreeTxt { get { return "机场操作"; } }
            public string Unit { get; set; }
            public double Price { get; set; }
            public double Quantity { get { return 1; } }
            public string Enterman { get { return Utils.GetCurrentUser().Operator; } }
            public string EnterDate { get { return DateTime.Now.ToString("yyyy-MM-dd HH:mm"); } }
            public string BaseType { get { return "A"; } }
            public string BaseEntry { get; set; }
            public string BaseSerialNum { get; set; }
            public string Cashier { get; set; }

        }
        protected class Charges : List<Charge>, IList<Charge>
        {
            private string _Cashier;
            private string _CardCode;
            public string CardCode
            {
                get { return _CardCode; }
                set
                {
                    SAPbobsCOM.Recordset rs = SAPBoAddon.B1Addon.B1Addon.SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
                    rs.DoQuery("SELECT U_Sale FROM OCRD Where CardCode = '" + value + "'");
                    _Cashier = rs.Fields.Item("U_Sale").Value;
                    _CardCode = value;
                }
            }
            public string CardName { get; set; }

            private string _BaseEntry;
            public string BaseEntry { get { return _BaseEntry; } set { _BaseEntry = value; } }

            private string _BaseSerialNum;
            public string BaseSerialNum { get { return _BaseSerialNum; } set { _BaseSerialNum = value; } }
            public Charge New()
            {
                Charge charge = new Charge();
                charge.Cashier = _Cashier;
                charge.BaseEntry = BaseEntry;
                charge.BaseSerialNum = BaseSerialNum;
                base.Add(charge);
                return charge;
            }
        }
        #endregion
        #endregion
        #region 取消账单
        private void CancelDelivery()
        {
            if (string.IsNullOrEmpty(SAPBoAddon.B1Assistant.Item.GetValue(CurrentForm, "Delivery").ToString().Trim()))
            {
                SBOApp.MessageBox("此单据没有账单，不需要取消。");
                return;
            }
            string DocEntry = CurrentForm.DataSources.DBDataSources.Item("@AVA_FF_OSTG").GetValue("DocEntry", 0).Trim();
            SAPbobsCOM.Recordset rs = SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
            if (SBOCompany.InTransaction == false) SBOCompany.StartTransaction();
            rs.DoQuery("SELECT U_Ref1 FROM [@AVA_FF_OSTG] Where DocEntry = " + DocEntry);
            string DeliveryNum = rs.Fields.Item("U_Ref1").Value;
            rs.DoQuery("SELECT CardCode FROM ODLN Where DocEntry = " + DeliveryNum);
            string CardCode = rs.Fields.Item("CardCode").Value;
            rs.DoQuery("SELECT COUNT('A') FROM DLN1 Where DocEntry = " + DeliveryNum);
            int LineCount = rs.Fields.Item(0).Value;
            SAPbobsCOM.Documents ReturnDelivery = SBOCompany.GetBusinessObject(BoObjectTypes.oReturns);
            ReturnDelivery.CardCode = CardCode;
            ReturnDelivery.DocDate = DateTime.Now;
            for (int i = 0; i < LineCount; i++)
            {
                ReturnDelivery.Lines.SetCurrentLine(ReturnDelivery.Lines.Count - 1);
                ReturnDelivery.Lines.BaseType = 15;
                ReturnDelivery.Lines.BaseEntry = int.Parse(DeliveryNum);
                ReturnDelivery.Lines.BaseLine = i;
                ReturnDelivery.Lines.Add();
            }
            if (ReturnDelivery.Add() != 0)
            {
                System.Runtime.InteropServices.Marshal.FinalReleaseComObject(ReturnDelivery);
                throw new Exception(SBOCompany.GetLastErrorCode().ToString() + " -- " + SBOCompany.GetLastErrorDescription());
            }
            System.Runtime.InteropServices.Marshal.FinalReleaseComObject(ReturnDelivery);
            rs.DoQuery("UPDATE [@AVA_FF_OSTG] SET U_Ref1 = '',U_Status = 'P' Where DocEntry = " + DocEntry);
            if (SBOCompany.InTransaction) SBOCompany.EndTransaction(BoWfTransOpt.wf_Commit);
            CurrentForm.Mode = BoFormMode.fm_FIND_MODE;
            SAPBoAddon.B1Assistant.Item.SetEnabled(CurrentForm, "3", true);
            SAPBoAddon.B1Assistant.Item.SetValue(CurrentForm, "3", DocEntry);
            CurrentForm.Items.Item("1").Click(BoCellClickType.ct_Regular);
        }
        #endregion
        #endregion
    }
}
